<script lang="ts">
  import { Body, ModalContent, Table, Icon } from "@budibase/bbui"
  import PasswordCopyTableRenderer from "./PasswordCopyTableRenderer.svelte"
  import { parseToCsv } from "@/helpers/data/utils"
  import { onMount } from "svelte"
  import InviteResponseRenderer from "./InviteResponseRenderer.svelte"
  import type { BulkUserCreated } from "@budibase/types"

  export let userData: { email: string; password: string }[]
  export let createUsersResponse: BulkUserCreated

  let hasSuccess: boolean
  let hasFailure: boolean
  let title: string
  let failureMessage: string

  let userDataIndex: Record<string, { password: string }>
  let successfulUsers: { email: string; password: string }[]
  let unsuccessfulUsers: { email: string; reason: string }[]

  const setTitle = () => {
    if (hasSuccess) {
      title = "Users created!"
    } else if (hasFailure) {
      title = "Oops!"
    }
  }

  const setFailureMessage = () => {
    if (hasSuccess) {
      failureMessage = "However there was a problem creating some users."
    } else {
      failureMessage = "There was a problem creating some users."
    }
  }

  const setUsers = () => {
    userDataIndex = userData.reduce<typeof userDataIndex>((prev, current) => {
      prev[current.email] = current
      return prev
    }, {})

    successfulUsers = createUsersResponse.successful.map(user => {
      return {
        email: user.email,
        password: userDataIndex[user.email].password,
      }
    })

    unsuccessfulUsers = createUsersResponse.unsuccessful.map(user => {
      return {
        email: user.email,
        reason: user.reason,
      }
    })
  }

  onMount(() => {
    hasSuccess = createUsersResponse.successful.length > 0
    hasFailure = createUsersResponse.unsuccessful.length > 0
    setTitle()
    setFailureMessage()
    setUsers()
  })

  const successSchema = {
    email: {},
    password: {},
  }

  const failedSchema = {
    email: {},
    reason: {},
  }

  const downloadCsvFile = () => {
    const fileName = "passwords.csv"
    const content = parseToCsv(["email", "password"], successfulUsers)

    download(fileName, content)
  }

  const download = (filename: string, text: string) => {
    const element = document.createElement("a")
    element.setAttribute(
      "href",
      "data:text/csv;charset=utf-8," + encodeURIComponent(text)
    )
    element.setAttribute("download", filename)

    element.style.display = "none"
    document.body.appendChild(element)

    element.click()

    document.body.removeChild(element)
  }
</script>

<!-- svelte-ignore a11y-no-static-element-interactions -->
<!-- svelte-ignore a11y-click-events-have-key-events -->
<ModalContent
  size="L"
  {title}
  confirmText="Done"
  showCancelButton={false}
  cancelText="Cancel"
  showCloseIcon={false}
>
  {#if hasFailure}
    <Body size="XS">
      {failureMessage}
    </Body>
    <Table
      schema={failedSchema}
      data={unsuccessfulUsers}
      allowEditColumns={false}
      allowEditRows={false}
      allowSelectRows={false}
      customRenderers={[
        { column: "reason", component: InviteResponseRenderer },
      ]}
    />
  {/if}
  {#if hasSuccess}
    <Body size="XS">
      All your new users can be accessed through the autogenerated passwords.
      Take note of these passwords or download the CSV file.
    </Body>

    <div class="container" on:click={downloadCsvFile}>
      <div class="inner">
        <Icon name="download" />

        <div style="margin-left: var(--spacing-m)">
          <Body size="XS">Passwords CSV</Body>
        </div>
      </div>
    </div>

    <Table
      schema={successSchema}
      data={successfulUsers}
      allowEditColumns={false}
      allowEditRows={false}
      allowSelectRows={false}
      customRenderers={[
        { column: "password", component: PasswordCopyTableRenderer },
      ]}
    />
  {/if}
</ModalContent>

<style>
  .inner {
    display: flex;
  }

  .container {
    width: 100%;
    height: var(--spectrum-alias-item-height-l);
    background: #009562;
    display: flex;
    justify-content: center;
    align-items: center;
  }
</style>
